package com.example.service;

import cn.hutool.core.date.DateUtil;
import com.example.entity.Trainorders;
import com.example.entity.Trainticket;
import com.example.exception.CustomException;
import com.example.mapper.TrainticketMapper;
import com.example.utils.TimeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 火车信息表业务处理
 **/
@Service
public class TrainticketService {

    @Resource
    private TrainticketMapper trainticketMapper;

    /**
     * 新增
     */
    public void add(Trainticket trainticket) {
        trainticketMapper.insert(trainticket);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        trainticketMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            trainticketMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Trainticket trainticket) {
        trainticketMapper.updateById(trainticket);
    }

    /**
     * 根据ID查询
     */
    public Trainticket selectById(Integer id) {
        return trainticketMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Trainticket> selectAll(Trainticket trainticket) {
        return trainticketMapper.selectAll(trainticket);
    }

    /**
     * 分页查询
     */
    public PageInfo<Trainticket> selectPage(Trainticket trainticket, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Trainticket> list = trainticketMapper.selectAll(trainticket);
        return PageInfo.of(list);
    }

    /**
     * 获取跟当前车次匹配的可改签的车次
     */
    public List<Trainticket> getChange(Trainorders trainorders) throws ParseException {
        // 1. 判断当前的时间是否已经过了发车的时间
        String now = DateUtil.now();
        String flyTime = trainorders.getFlyTime();
        if (!TimeUtils.compareDate(flyTime, now, "yyyy-MM-dd HH:mm:ss")) {
            throw new CustomException("-1", "您的车次已发车，无法改签");
        }
        // 查询出待改签的车次
        Integer ticketId = trainorders.getTicketId();
        Trainticket trainticket = trainticketMapper.selectById(ticketId);
        // 查询所有的车次
        List<Trainticket> traintickets = trainticketMapper.selectAll(new Trainticket());
        // 筛选可改签的车次
        return traintickets.stream()
                .filter(x -> x.getStartCity().equals(trainticket.getStartCity())
                        && x.getEndCity().equals(trainticket.getEndCity())
                        && x.getNum() >= trainorders.getNum()
                        && !x.getId().equals(ticketId))
                .collect(Collectors.toList());
    }
}